/**
 * %base-reportquery%
 * %v1.0%
 */
package com.leehom.arch.base.reportquery.dynsql;

import java.io.Serializable;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.leehom.arch.base.reportquery.TypeEnum;

import lombok.Data;

/**
 * @类名: DynSql
 * @说明: 动态sql
 *
 * @author   leehom
 * @Date	 2020年8月22日 上午10:20:45
 * 修改记录：
 *   > 增加动态块
 *
 * @see 	 
 *   
 * 
 *  
 */
@Data
public class DynSql implements Serializable {
	
	/** */
	private static final long serialVersionUID = 300133421209896780L;
	
	/** 动态块占位符*/
	public static final String DYN_PIECE_PLACE_HOLDER = "###";
	public static final String PLACE_HOLDER_PATTERN = "{###}";
	/** */
	private String name;
	/** sql模板*/
	private String sqlTemplate;
	/** 结果类型*/
	private Class resultClazz;
	/** sql动态块*/
	private List<SqlPiece> pieces;
	/** 参数类型map*/
	private Map<String, TypeEnum> paramTypeMap;
	private Map<String, SqlPiece> pieceMap;
	
	public void init() {
		paramTypeMap = new HashMap<>();
		pieceMap = new HashMap<>();
		for(SqlPiece p : pieces) {
			paramTypeMap.put(p.getParamName(), p.getParamType());
			pieceMap.put(p.getParamName(), p);
		}
	}
	
	// 动态增加动态块
	public void addPieces(List<SqlPiece> addings) {
		// 占位符
		StringBuilder holderStr = new StringBuilder();
		//
		for(SqlPiece piece:addings) {
			pieces.add(piece);
			pieceMap.put(piece.getParamName(), piece);
			addAuthStr(holderStr, pieces.size()-1);
			holderStr.append(" ");
		}
		//
		sqlTemplate = sqlTemplate.replaceFirst(DYN_PIECE_PLACE_HOLDER, holderStr.toString());
		
	}
	
	private void addAuthStr(StringBuilder authStr, int count) {
		String holderStr = PLACE_HOLDER_PATTERN.replaceAll(DYN_PIECE_PLACE_HOLDER, Integer.toString(count));
		authStr.append(holderStr);
	}
	
	/**
	 * @说明：构建sql
	 *
	 * @author leehom
	 * @param params
	 * @param values
	 * @return
	 * 
	 */
	public String buildSQL(Map<String, Object> params) {
		//
		String sql = null;
		if(pieces!=null) {
			Object[] blocks = new Object[pieces.size()];  
			for(int i=0;i<blocks.length;i++) {
				blocks[i] = pieces.get(i).getPiece(params);
				
			}
			sql = MessageFormat.format(sqlTemplate, blocks); 
		} else {
			sql = sqlTemplate; 
		}
		//   
		return sql;
	}
	
}
